package org.deng.vertx.web.controller;

import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: DengLibin
 * @Date: Create in 2022-04-30 15:08:35
 * @Description: 
 */
@Slf4j
public class HelloController implements RouterController{

    private Vertx vertx;
    public HelloController(Vertx vertx){
        this.vertx = vertx;
    }
    @Override
    public void configRouter(Router router) {
        log.info("配置HelloController");
        router.route("/hello").method(HttpMethod.GET).handler(this::index);
        router.route("/hello/:name").method(HttpMethod.GET).handler(this::helloName);
        router.route("/helloServerError").method(HttpMethod.GET).handler(this::serverError);

        
    }

    private void index(RoutingContext ctx) {
        //发送消息
        vertx.eventBus().request("hello.vertx.addr", "", reply ->{
            ctx.request().response().end((String) reply.result().body());
        });
    }

    private void helloName(RoutingContext ctx) {
        String name = ctx.pathParam("name");
        //发送消息
        vertx.eventBus().request("hello.named.addr", name, reply -> {
            HttpServerResponse response =  ctx.request().response();
            response.headers().set("Content-Type", "application/json;charset:utf-8");
            response.end((String) reply.result().body());
        });
    }

    /**
     * 错误捕捉测试
     * @param ctx
     */
    private void serverError(RoutingContext ctx){
        ctx.end((1/0)+"");
    }
    
}
